import { Session } from '@/utils/storage';
import { formatDate, formatAxis } from '@/utils/formatTime';
import { PrevLoading } from '@/utils/loading.js';
import { resetRouter } from "@/router/index";
import { validUser } from '@/utils/validate'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUser(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value !== "1234") {
        callback(new Error('验证码不正确'))
      } else {
        callback()
      }
    }
    return {
      quotationsList: [
        {
          name: '颜渊',
          comeFrom: '论语',
          content:
            '自己不喜欢的，就不要强加给别人。饥寒是自己不喜欢的，不要把它强加给别人；耻辱是自己不喜欢的，也不要把它强加给别人。将心比心，推己及人，从自己的利与害想到对别人的利与害，多替别人着想，这是终生应该奉行的原则。',
        },
        {
          name: '荀子',
          comeFrom: '劝学',
          content:
            '木料经过木工用墨线（木工用具）划直线加工以后，就变直了；金属物品在磨刀石上磨砺后，就能锋利。人经过学习磨练，自我反省，就会变得聪慧明智，不犯错误，也越来越坚强。',
        },
        {
          name: '里仁',
          comeFrom: '论语',
          content:
            '见到贤人，就应该想着向他学习；看见不贤的人，便应该自己反省，对不如自己的人喜欢讥笑、轻视，因而沾沾自喜；对比自己强的人喜欢贬低，甚至嫉妒、畏惧退缩，害怕与他们交往：这都是不正确的态度。',
        },
        {
          name: '述而',
          comeFrom: '论语',
          content:
            '君子心地平坦宽广，小人却经常局促忧愁。君子襟怀坦白，安贫乐业，与人为善，知足常乐，所以能坦荡荡。小人欲念太多，患得患失，忧心忡忡，怨天尤人，局促不安，所以常心怀戚戚。',
        },
        {
          name: '老子',
          comeFrom: '第六十四章',
          content:
            '千里遥远的路程是从脚下第一步开始的。任何事情的成功都是从头开始，从小到大逐渐积累的。万事开头难，没有个开头就不会有结果。任何事情都要从一点一滴的小事开始做起。',
        },
        {
          name: '朱熹',
          comeFrom: '训学斋规',
          content:
            '读书有三到，谓心到，眼到，口到。心不在此，则眼看不仔细，心眼既不专一，却只漫浪诵读，决不能记，久也不能久也。三到之中，心到最急，心既到矣，眼口岂不到乎？',
        },
      ],
			quotations: {},
			isView: false,
			submit: {
				loading: false,
			},
			loginForm: {
				userName: 'admin',
				password: '123456',
				code: '1234',
			},
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        code: [{ required: true, trigger: 'blur', validator: validateCode }]
      },
			time: {
				txt: '',
				fun: null,
			},
    }
  },
  computed: {
		// 获取当前时间
		currentTime() {
			return formatAxis(new Date());
		},
		// 获取布局配置信息
		getThemeConfig() {
			return this.$store.state.themeConfig.themeConfig;
		},
	},
  created() {
		this.initTime();
	},
  mounted() {
		this.initRandomQuotations();
	},
  methods: {
    // 随机语录
		initRandomQuotations() {
			this.quotations = this.quotationsList[Math.floor(Math.random() * this.quotationsList.length)];
		},
    // 初始化左上角时间显示
		initTime() {
			this.time.txt = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS WWW QQQQ');
			this.time.fun = setInterval(() => {
				this.time.txt = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS WWW QQQQ');
			}, 1000);
		},
    submitForm() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.submit.loading = true;

          this.$axios({
            method: "post",
            url: "api/admin/sysAdminSys/login",
            data: {
              name: this.loginForm.username,
              password: this.loginForm.password
            }
          }).then(res => {
            if (res.data.code !== 200) {
              this.$message({
                message: "登录失败",
                type: "error"
              });
              return;
            }
    
            Session.set('uObj', JSON.stringify(res.data.data.admin));
            Session.set('z-admin-token', res.data.data.jwtToken);
    
            sessionStorage.setItem("uObj", JSON.stringify(res.data.data.admin));
            sessionStorage.setItem("z-admin-token", res.data.data.jwtToken);
            localStorage.setItem("z-admin-token", res.data.data.jwtToken);
    
            // 将当前登录人的shiroKey集合存储到sessionStorage
            sessionStorage.setItem("tRoleLists", JSON.stringify(res.data.data.admin.rights));
            sessionStorage.setItem("rolesUuid", JSON.stringify(res.data.data.admin.rolesUuid));
            sessionStorage.setItem("roleRange", res.data.data.admin.roleRange);
    
            PrevLoading.start();
    
            console.log('login');
            // 查询菜单
            this.$axios({
              method: "get",
              url: "/api/sys/sysMenu/findMenuList"
            }).then(resN => {
              if (resN.data.code !== 200) {
                this.$message({
                  message: "登录失败",
                  type: "error"
                });
                return;
              }
    
              console.log('---', resN.data.data);
              const routeData = resN.data.data;
              sessionStorage.setItem("routeData", JSON.stringify(routeData));
              resetRouter();
    
              if (res.data.data.admin.rights.length > 0) {
                let firstPath = "";
                for (let i = 0; i < res.data.data.admin.rights.length; i ++) {
                  for (let j = 0; j < routeData.length; j++) {
                    if (routeData[j].shiroKey === res.data.data.admin.rights[i] 
                        // && routeData[j].fileLocation !== "ParentView" 
                        && routeData[j].icon !== null 
                        && routeData[j].icon !== "") {
                          if (routeData[j].fileLocation === "ParentView") {
                            firstPath = routeData[j].path + '/' + routeData[j].children[0].path + '';
                          } else {
                            firstPath = routeData[j].path;
                          }
                      break;
                    }
                  }
                }
                this.$router.push(firstPath);
              } else {
                this.$message({
                  message: "登录失败",
                  type: "error"
                });
                return;
              }
            });
          });
        }
      });
    }
  },
  destroyed() {
		clearInterval(this.time.fun);
	},
}